/**
 * 工具类,所有方法放到一个对象中,方便维护命名和定位
 * (PS:注册到JQUERY时命名如果不注意可能冲突)
 * 命名规则:工具+行为
 * @author: ZL
 * @version 1.0.0
 */

/**
 * 异步请求ajax
 * 请求地址：requestUrl
 * JSON对象: params
 * 回调方法: callBack
 */
zUtil.ajaxGet = function(requestUrl, params, callBack) {
    return zUtil.ajaxFunc(requestUrl, params, "GET", callBack, true);
};
zUtil.ajaxPost = function(requestUrl, params, callBack) {
    return zUtil.ajaxFunc(requestUrl, params, "POST", callBack, true);
};
zUtil.ajaxPut = function(requestUrl, params, callBack) {
    return zUtil.ajaxFunc(requestUrl, params, "PUT", callBack, true);
};
zUtil.ajaxDelete = function(requestUrl, params, callBack) {
    return zUtil.ajaxFunc(requestUrl, params, "DELETE", callBack, true);
};
/**
 * 同步请求ajax
 * 请求地址：requestUrl
 * JSON对象: params
 */
zUtil.ajaxGetAsync = function(requestUrl, params) {
    return zUtil.ajaxFunc(requestUrl, params, "GET", null, false);
};
zUtil.ajaxPostAsync = function(requestUrl, params) {
    return zUtil.ajaxFunc(requestUrl, params, "POST", null, false);
};
zUtil.ajaxPutAsync = function(requestUrl, params) {
    return zUtil.ajaxFunc(requestUrl, params, "PUT", null, false);
};
zUtil.ajaxDeleteAsync = function(requestUrl, params) {
    return zUtil.ajaxFunc(requestUrl, params, "DELETE", null, false);
};
/**
 * 自行传参,默认同步,直接返回结果
 * options：参数配置对象{}
 */
zUtil.ajaxGetCustom = function(options) {
    options.type = "GET";//强制设置为GET
    return zUtil.ajaxCustomFunc(options);
};
zUtil.ajaxPostCustom = function(options) {
    options.type = "POST";//强制设置为POST
    return zUtil.ajaxCustomFunc(options);
};
zUtil.ajaxPutCustom = function(options) {
    options.type = "PUT";//强制设置为PUT
    return zUtil.ajaxCustomFunc(options);
};
zUtil.ajaxDeleteCustom = function(options) {
    options.type = "DELETE";//强制设置为DELETE
    return zUtil.ajaxCustomFunc(options);
};
zUtil.ajaxForm = function(requestUrl, params) {
    var opts =  {
            type: 'POST',
            url: requestUrl,
            data: params,
//            contentType : "multipart/form-data",
            cache : false,
            async : false,
            success: function(result,status,xhr){
            
            },
            error : function(xhr,status,error) {
//                zUtil.msg("Network Exception");
                return null;
            },
            beforeSend: function(){
                zUtil.progress();
            },
            complete: function(){
                zUtil.progress("close");
            }
    };
    $.ajax(opts);
};
//ajax固定传参
zUtil.ajaxFunc = function(requestUrl, params, method, callBack, sync) {
    var data = null;
    var opts =  {
            type: method,
            url: requestUrl,
            data: {},
            dataType: "json",
            contentType : "application/json;charset=utf-8",
            cache : false,
            async : sync,
            success: function(result,status,xhr){
                if(callBack){//有回调方法
                    callBack(result);//自行处理
                }else{
                    data = result;
                }
            },
            error : function(xhr,status,error) {
//                zUtil.msg("Network Exception");
                return null;
            },
            beforeSend: function(){
                zUtil.progress();
            },
            complete: function(){
                zUtil.progress("close");
            }
      };
    
    if(params){
        var queryStr = params;
        if(method == "GET"){
//            queryStr = $.param(queryStr);//自动转换为查询字符串
            opts.contentType = "application/x-www-form-urlencoded;charset=utf-8";
        }else{
            queryStr = JSON.stringify(params);
        }
        opts.data = queryStr;
    }
    
    $.ajax(opts);
    return data;//ajaxs.responseJSON;
};
//ajax自定传参
zUtil.ajaxCustomFunc = function(options) {
    var data = null;
    var opts =  $.extend(true,{
            type: '',//GET/POST/PUT/DELETE
            url: '',
            data: {},
            dataType: "json",
            contentType : "application/json;charset=utf-8",
            cache : false, //false:不缓存
            async : false, //false:同步
//            beforeSend:function(xhr){//发送请求前可修改 XMLHttpRequest 对象的函数
//                //add code
//            },
//            dataFilter:function(data,type){// // 对Ajax返回的原始数据进行预处理
//                //add code
//            },
            success: function(result,status,xhr){
                data = result;
            },
            error : function(xhr,status,error) {
//                zUtil.msg("Network Exception");
                return null;
            },
            beforeSend: function(){
                zUtil.progress();
            },
            complete: function(){
                zUtil.progress("close");
           }
        }, options);
    if(opts.data){
        var queryStr = opts.data;
        if(method == "GET"){
//            queryStr = $.param(queryStr);//转换为查询字符串
            opts.contentType = "application/x-www-form-urlencoded;charset=utf-8";
        }else{
            queryStr = JSON.stringify(queryStr);//参数带上JSON.stringify();
        }
        opts.data = queryStr;
    }
    
    $.ajax(opts);
    return data;//ajaxs.responseJSON;
};


//uuid
zUtil.uuid = function(){
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
        });
};


/**
 * 根据名字获取对象值，简化多级判断，默认没有则返回null
 * object         数据对象 {}
 * path           路径 result.data.data或result.data.data[],result.data.data[0]
 * defaultValue   查找为空时的默认值,一般需要用到null或""
 */
zUtil.getVal = function(object, path, defaultValue) {
    var value = null;
        if(!$.isEmptyObject(object) && "object" === $.type(object) && path){
            var paths = path.split('.');
            var length = paths.length;
            $.each(paths,function(i,v){
                var aidx = v.lastIndexOf("[");
                if(aidx > 0){
                    //如果结构不匹配数组,则直接返回null
                    if("array" === $.type(object)){
                        var name = v.substring(0,aidx);
//                        console.log(name);
                        var sidx= v.substring(aidx+1,v.lastIndexOf("]"))
                        if(!sidx){//取全部数组
                            var tmp = [];
                            for(var oi=0,ln = object.length;oi < ln; oi++){
                                tmp.push((object[oi])[name]);
                            }
                            object = tmp;
                        }else{
                            object = (object[sidx])[name];
                        }
                        if(length-1 == i && "undefined" !== $.type(object)){
                            value = object;
                        }
                        if("object" !== $.type(object) && "array" !== $.type(object)){
                            return false;
                        }
                    }else{
                        return false;
                    }
                }else{
                    object = object[v];
                    
                    if(length-1 == i && "undefined" !== $.type(object)){
                        value = object;
                    }
                    if("object" !== $.type(object) && "array" !== $.type(object)){
                        return false;
                    }
                }
            });
        }
        if(value == null && "undefined" !== $.type(defaultValue)){
            value = defaultValue;
        }
        return value;
};
/**对象取值/赋值**/
zUtil.deepVal = function(object, path, defaultValue) {
    path = ("array" !== $.type(path)) ? path.replace(/\[/g, '.').replace(/\]/g, '').split('.') : path;
    
    //根据路径创建对象
    const createObject = (path, value) => {
      let keyPath = [];
      if ("array" === $.type(path)) {
          keyPath = [...path];
      }
      if (keyPath.length) {
        const key = keyPath.shift();
        if ("number" === $.type(key)) {
          const object = new Array(key + 1);
          object[key] = createObject(keyPath, value);
          return object;
        } else{
            return { [key]: createObject(keyPath, value) };
        }
      } else{
          if("array" === $.type(value)){
              return $.extend(true,[], value);
          }
          else if("object" === $.type(value)){
              return $.extend(true,{}, value);
          }
          else{
              return value;
          }
      }
    };
    // 根据路径赋值
    const setPathValue = (object, path, value) => {
      let keyPath = [];
      if ("array" === $.type(path)){
          keyPath = [...path];
      }
      if (keyPath.length) {
        const key = keyPath.shift();
        if (object && object[key]){
            object[key] = setPathValue(object[key], keyPath, value);
        }
        else{
            object[key] = createObject(keyPath, value);
        }
      } else{
          if("array" === $.type(value)){
              object = $.extend(true,[], value);
          }
          else if("object" === $.type(value)){
              object = $.extend(true,{}, value);
          }
          else{
              object = value;
          }
      }
      return object;
    };
    // 根据路径取值
    const getPathValue = (object, path) => {
      let keyPath = [];
      if ("array" === $.type(path)){
          keyPath = [...path];
      }
      else if ("string" === $.type(path) || "number" === $.type(path)){
          keyPath = [path];
      }
      while (keyPath.length) {
        const key = keyPath.shift();
        if (!object){
            return undefined;
        }
        object = object[key];
      }
      return object;
    };
    
    if("undefined" !== $.type(defaultValue)){
      return setPathValue(object, path, defaultValue);
    }else{
      return getPathValue(object, path);
    }
};


zUtil.parse = function(obj,option) {
    var opts = $.extend({
        flag: false,
    },option);
    try{
       if(!opts.flag){
          return JSON.parse(obj);
       }else{
          var result = JSON.parse(obj,function(k,v){
              if(v.indexOf && v.indexOf('function') > -1){
                 return eval("(function(){return "+v+" })()")
              }
              return v;
          });
          return result;
       }
   }catch(b){
       console.log(b);
       return null;
   }
}
zUtil.strify = function(obj,option) {
    var opts = $.extend(true,{
        flag: false,
        indent: 4,
        indentFlag: false,
    },option);
    try{
       if(!opts.flag){
           if(!opts.indentFlag){
               return JSON.stringify(obj);
           }else{
               return JSON.stringify(obj,null,opts.indent);
           }
       }else{
           var result =JSON.stringify(obj, function(key, val) {
                if (typeof val === 'function') {
                  return val + '';
                }
                return val;
           });
           return result;
       }
   }catch(b){
       console.log(b);
       return null;
   }
}
zUtil.clip = function(id,options) {
     var clipboard = new ClipboardJS(id);
     
     if("undefined" != $.type(options) && options.success){
         clipboard.on('success', options.success);
     }else{
         clipboard.on('success', function(e) {
             var msg = "已复制";
             if("undefined" === $.type(options) || options.show){
                 msg = msg +" "+ e.text;
             }
             zUtil.Toastr("success",msg + e.text);
             e.clearSelection();
         });
     }
     if("undefined" != $.type(options) && options.error){
         clipboard.on('error', options.error);
     }else{
       clipboard.on('error', function(e) {
           zUtil.Toastr("error","复制失败");
           e.clearSelection();
       });
     }
     return clipboard;
}


/**
 * 屏蔽默认的右键菜单即可onload="noright(document.body);"
 */
function noright(obj) {
    if (obj) {
//        obj.oncontextmenu  =  function() {
//            return false;
//        }
        
//         obj.ondragstart  =  function() {
//             return false;
//         }
//         obj.onselectstart  =  function() {
//             return false;
//         }
//         obj.onselect  =  function() {
//             obj.selection.empty();
//         }
//         obj.oncopy  =  function() {
//             obj.selection.empty();
//         }
//         obj.onbeforecopy  =  function() {
//             return false;
//         }
    }
}




/**赋值/取值**/
zUtil.valAll = function(id,data,options){
    var opts = $.extend(true, {
       clearForm: true,
       voTag: "cpt-vo",
       listTag: "cpt-list",
       arrayVal:true,
    }, options);
    var voTag =opts.voTag;
    var listTag =opts.listTag;
    if("undefined" === $.type(data)){
        function getValues(id,path,lv){
            data = {};
            var valfunc = function(ex,namex){
                var hasVal = zUtil.deepVal(data,namex);
                var currVal = zUtil.val(ex);
                if("undefined" === $.type(hasVal) || hasVal === null){
                    if("checkbox" === $(ex).prop('type')){
//                        console.log("1 >>>>>>"+namex);
//                        console.log(currVal);
                        data = zUtil.deepVal(data, namex, currVal!=null?[currVal]:null);
                    }else if("radio" === $(ex).prop('type')){
//                        console.log("5 >>>>>>"+namex);
//                        console.log(currVal);
                        data = zUtil.deepVal(data, namex, currVal!=null?currVal:null);
                    }else{
//                        console.log("2 >>>>>>"+namex);
//                        console.log(currVal);
                        data = zUtil.deepVal(data, namex, currVal);
                    }
                }else{
                    if("array" === $.type(hasVal) && ("checkbox" === $(ex).prop('type'))){
//                        console.log("3 >>>>>>"+namex);
//                        console.log(currVal);
                        data = zUtil.deepVal(data, namex, $.merge(hasVal,currVal!=null?[currVal]:[]));
                    }else if("radio" === $(ex).prop('type')){
//                        console.log("6 >>>>>>"+namex);
//                        console.log(currVal);
                        data = zUtil.deepVal(data, namex, currVal!=null?currVal:hasVal);
                    }else{
//                        console.log("4 >>>>>>"+namex);
//                        console.log(currVal);
                        data = zUtil.deepVal(data, namex, currVal);
                    }
                }
            }
            $(id).find(':input[name],label[name],span[name]').each(function(i,e){
                var name = $(e).attr('name');
                if(name){
                    var groups = $(e).parents('['+voTag+']');
                    var list = $(e).parents('['+listTag+']');
                    if(groups.length > 0){
                        var gropupath2 = [];
                        for(var ig=groups.length-1;ig>=0;ig--){
                            gropupath2.push($(groups[ig]).attr(voTag));
                        }
                        gropupath2.push(name);
                        valfunc(e,gropupath2);
                    }
                    else if(list.length > 0){
                        
                    }
                    else{
                        valfunc(e,name);
                    }
                }
            });
        };
        
        getValues(id,data);
        
        if(opts.arrayVal && data){
           var handleArrVal = function(dt){
              $.each(dt,function(key,val){
                   if("array" === $.type(val)){
                      if(val.length === 0){
                          dt[key] = null;
                      }else if("object" === $.type(val[0])){
                         handleArrVal(val);
                      }else if("array" === $.type(val[0])){
                         handleArrVal(val);
                      }else {
                         dt[key] = val.toString();
                      }
                   } else if("object" === $.type(val)){
                       handleArrVal(val);
                   }
              });
           }
           
           handleArrVal(data);
        }
        return data;
    }else{
        if(opts.clearForm){
            zUtil.formClear(id);
        }
        function getParentsGroupLvl(e,neme){
            var groups = $(e).parents('['+voTag+']');
            if(groups.length > 0){
                var gropupath2 = [];
                for(var ig=groups.length-1;ig>=0;ig--){
                    gropupath2.push($(groups[ig]).attr(voTag));
                }
               return gropupath2.join(".");
            }
            return null;
        }
        function setValues(id,data,prelevel){
            var el = $(id);
            if("object" === $.type(data)){
                $.each(data,function(key,value){
                    if("undefined" === $.type(value)){
                        value = null;
                    }
                    
                    if(("array" !== $.type(value) && "object" !== $.type(value))
                        || ("array" === $.type(value) && "object" !== $.type(value[0]))){
                        var cids = ':input[name='+key+'],label[name='+key+'],span[name='+key+']';
                        el.find(cids).each(function(i,e){
                            var glevel = getParentsGroupLvl(e,key);
                            if(glevel === prelevel){
                                zUtil.val(e,value);
                            }
                        });
                    }
                    else if("object" === $.type(value)){
                        el.find('['+voTag+'='+key+']').each(function(i2,e2){
                            var nlevel = prelevel != null?prelevel + "." + key:key;
                            setValues(e2,value,nlevel);
                        });
                    }
                    else if("array" === $.type(value) && "object" === $.type(value[0])){
                        //肯定是表格赋值
                        el.find('['+listTag+'='+key+']').each(function(i,e){
                            var glevel = getParentsGroupLvl(e,key);
                            if(glevel === prelevel){
                                
                            }
                        });
                    }
                });
            }
            else if("array" === $.type(data) && "object" === $.type(data[0])){
                //肯定是表格赋值
            }
        }
        
        setValues(id,data,null);
    }
}
zUtil.val = function(id,val,options){
    var el = $(id);
    
    var tagName = el.prop("tagName");
    var type = el.prop("type");
    var name = el.attr('name');
    
      var opts = {
//            gFormat: function(name,value){},//指定格式转换为指定格式
//            gName: {xxx:转换方法, xxx:转换方法,...},//指定NAME转换为指定格式
//            sFormat: function(name,value){},//指定格式转换为指定格式
//            sName: {xxx:转换方法, xxx:转换方法,...},//指定NAME转换为指定格式
              arrayVal: true,
      };
      opts = $.extend(true,opts,options);
      
      var formatEx = function(keyName,keyVal,type){
          var covertEx = function(keyName,keyVal){
              if('undefined' !== $.type(opts[fname2]) && opts[fname2] !== null){
                  if(opts[fname2][keyName]){
                      return opts[fname2][keyName](keyVal,keyName);
                  }
              }
              if('undefined' !== $.type(opts[fname1]) && opts[fname1] !== null){
                  return opts[fname1](keyVal,keyName);
              }
              return keyVal;
          }
          try{
              var  fname1 = type?"gFormat":"sFormat";
              var  fname2 = type?"gName":"sName";
              if('array' === $.type(keyVal) && 'object' !== $.type(keyVal[0])){
                  var newArr = [];
                  $.each(keyVal,function(i,ival){
                      newArr.push(covertEx(keyName,ival));
                  });
                  return newArr;
              }else{
                  return covertEx(keyName,keyVal);
              }
          }catch(b){
              
          }
          return keyVal;
    };
    
    if("undefined" === $.type(val)){
        val = null;
        
        if("LABEL" === tagName || "SPAN" === tagName){
            val = el.html();
        }
        else if(el.parent().hasClass('bootstrap-select')) {
            val = el.selectpicker('val');
        }
        else if("undefined" !== $.type(tagName)) {
            if("SELECT" === tagName){
                val = el.val();
            }else if("INPUT" === tagName){
                if("checkbox" === type){
                    var ckStatus = el.prop('checked');
                    if("undefined"!== $.type(ckStatus) && ckStatus){
                        val =  el.val();
                    }
                }else if("radio" === type){
                    var ckStatus = el.prop('checked');
                    if("undefined"!== $.type(ckStatus) && ckStatus){
                        val =  el.val();
                    }
                }else {
                    val = el.val();
                }
            }else if("TEXTAREA" === tagName){
                val = el.val();
            }else{
                val = el.val();
            }
        }
        val = formatEx(name,val,true);
        if(opts.arrayVal && "array" === $.type(val)){
            val = val.length>0 ? val.toString() : null;
        }
        if(val === ""){
          val = null;
        }
        return val;
    }else{
        val = formatEx(name,val,false);
        
        if("LABEL" === tagName || "SPAN" === tagName){
            el.html(val);
        }
        else if(el.parent().hasClass('bootstrap-select')) {
            el.selectpicker('val',val);
        }
        else if("undefined" !== $.type(tagName)) {
            if("SELECT" === tagName){
                el.val(val);
            }else if("INPUT" === tagName){
                if("checkbox" === type){
                    if(val && ("array" === $.type(val) || "string" === $.type(val))){
                        if("string" === $.type(val)){
                            val = val.split(",");
                        }
                        $.each(val,function(i,item){
                            if(el.is('[value='+item+']')){
                                el.prop('checked','true');
                            }
                        });
                    }
                }else if("radio" === type){
                    if(el.is('[value='+val+']')){
                        el.prop('checked','true');
                    }
                }else{
                    el.val(val);
                }
            }else if("TEXTAREA" === tagName){
                el.val(val);
            }else{
                el.val(val);
            }
        }
    }
};




(function($){
  
}(jQuery));